<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getTeacherInfoAPI, updateTeacherInfoAPI } from '../../../api/teacher'

// 教师信息数据
const teacherInfo = ref({
  id: '',
  name: '',
  teacherNo: '',
  gender: '',
  department: '',
  email: '',
  phone: '',
  title: '',
  office: ''
})

// 是否处于编辑状态
const isEditing = ref(false)

// 获取教师信息
const getTeacherInfo = async () => {
  try {
    const data = await getTeacherInfoAPI()
    teacherInfo.value = data
  } catch (error) {
    ElMessage.error(error || '获取信息失败')
  }
}

// 保存教师信息
const saveTeacherInfo = async () => {
  try {
    await updateTeacherInfoAPI(teacherInfo.value)
    isEditing.value = false
    ElMessage.success('保存成功')
    // 重新获取最新数据
    await getTeacherInfo()
  } catch (error) {
    ElMessage.error(error || '保存失败')
  }
}

onMounted(() => {
  getTeacherInfo()
})
</script>

<template>
  <div class="teacher-info">
    <div class="header">
      <h2>个人信息</h2>
      <el-button v-if="!isEditing" type="primary" @click="isEditing = true">编辑</el-button>
      <template v-else>
        <el-button @click="isEditing = false">取消</el-button>
        <el-button type="primary" @click="saveTeacherInfo">保存</el-button>
      </template>
    </div>

    <el-form :disabled="!isEditing" label-width="100px">
      <el-form-item label="教师姓名">
        <el-input v-model="teacherInfo.name" />
      </el-form-item>
      <el-form-item label="工号">
        <el-input v-model="teacherInfo.teacherNo" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="teacherInfo.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属院系">
        <el-input v-model="teacherInfo.department" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="teacherInfo.email" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="teacherInfo.phone" />
      </el-form-item>
      <el-form-item label="职称">
        <el-input v-model="teacherInfo.title" />
      </el-form-item>
      <el-form-item label="办公室">
        <el-input v-model="teacherInfo.office" />
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
.teacher-info {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }
}
</style>
